package cn.edu.baiyunu.myapplication.ui.screens.home.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.edu.baiyunu.myapplication.data.model.Category
import cn.edu.baiyunu.myapplication.data.model.Transaction
import cn.edu.baiyunu.myapplication.data.repository.CategoryRepository
import cn.edu.baiyunu.myapplication.data.repository.SettingsRepository
import cn.edu.baiyunu.myapplication.data.repository.TransactionRepository
import cn.edu.baiyunu.myapplication.ui.utils.getCurrentMonth
import cn.edu.baiyunu.myapplication.ui.utils.getCurrentYear
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 首页ViewModel
 */
@HiltViewModel
class HomeViewModel @Inject constructor(
    private val transactionRepository: TransactionRepository,
    private val categoryRepository: CategoryRepository,
    private val settingsRepository: SettingsRepository
) : ViewModel() {
    // UI状态
    private val _uiState = MutableStateFlow(
        HomeUiState(
            currentYear = getCurrentYear(),
            currentMonth = getCurrentMonth()
        )
    )
    val uiState: StateFlow<HomeUiState> = _uiState.asStateFlow()
    
    init {
        // 初始化数据
        initData()
    }
    
    /**
     * 初始化数据，加载月度收支汇总和最近交易
     */
    private fun initData() {
        viewModelScope.launch {
            try {
                // 初始化分类
                categoryRepository.initDefaultCategories()
                
                // 初始化设置
                settingsRepository.initDefaultSettings()
                
                // 初始化示例交易数据
                transactionRepository.initSampleData()
                
                // 加载用户名
                loadUsername()
                
                // 加载当月汇总和最近交易
                loadMonthlySummary()
                loadRecentTransactions()
                
                // 加载分类数据
                loadCategories()
            } catch (e: Exception) {
                _uiState.update { 
                    it.copy(error = "加载数据失败: ${e.message}", isLoading = false) 
                }
            }
        }
    }
    
    /**
     * 加载用户名
     */
    private fun loadUsername() {
        viewModelScope.launch {
            settingsRepository.getSettings()
                .collect { settings ->
                    _uiState.update { 
                        it.copy(username = settings?.username ?: "用户") 
                    }
                }
        }
    }
    
    /**
     * 加载月度汇总
     */
    private fun loadMonthlySummary() {
        viewModelScope.launch {
            val year = _uiState.value.currentYear
            val month = _uiState.value.currentMonth
            
            transactionRepository.getMonthlySummary(year, month)
                .collect { summary ->
                    _uiState.update { 
                        it.copy(
                            monthlyIncome = summary.totalIncome,
                            monthlyExpense = summary.totalExpense,
                            monthlyBalance = summary.balance,
                            isLoading = false
                        ) 
                    }
                }
        }
    }
    
    /**
     * 加载最近交易
     */
    private fun loadRecentTransactions() {
        viewModelScope.launch {
            transactionRepository.getRecentTransactions(5)
                .collect { transactions ->
                    _uiState.update { 
                        it.copy(
                            recentTransactions = transactions,
                            isLoading = false
                        ) 
                    }
                }
        }
    }
    
    /**
     * 加载所有分类到映射表
     */
    private fun loadCategories() {
        viewModelScope.launch {
            val expenseFlow = categoryRepository.getExpenseCategories()
            val incomeFlow = categoryRepository.getIncomeCategories()
            
            combine(expenseFlow, incomeFlow) { expenses, incomes ->
                val allCategories = expenses + incomes
                allCategories.associateBy { it.id }
            }.collect { categoryMap ->
                _uiState.update { 
                    it.copy(categoryMap = categoryMap) 
                }
            }
        }
    }
    
    /**
     * 更新当前年月
     */
    fun updateCurrentYearMonth(year: Int, month: Int) {
        if (_uiState.value.currentYear == year && _uiState.value.currentMonth == month) {
            return // 如果年月没有变化，则不更新
        }
        
        _uiState.update { 
            it.copy(
                currentYear = year,
                currentMonth = month,
                isLoading = true
            ) 
        }
        
        loadMonthlySummary()
    }
    
    /**
     * 获取分类
     */
    fun getCategoryById(categoryId: String): Category? {
        return _uiState.value.categoryMap[categoryId]
    }
} 